package com.umeox.watch.moto.gallery.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;

import com.umeox.moto.common.utils.AndroidUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class BitmapUtil {

    private static final Bitmap.CompressFormat FORMAT = Bitmap.CompressFormat.JPEG;
    private static final int QUALITY = 80;

    public static Bitmap scale(Bitmap src, int newWidth, int newHeight) {
        return scale(src, newWidth, newHeight, false);
    }

    public static Bitmap scale(Bitmap src, int newWidth, int newHeight, boolean recycle) {

        Bitmap ret = Bitmap.createScaledBitmap(src, newWidth, newHeight, true);
        if (recycle && !src.isRecycled()) {
            src.recycle();
        }
        return ret;
    }

    public static Bitmap clip(Bitmap src, int x, int y, int width, int height) {
        return clip(src, x, y, width, height, false);
    }


    public static Bitmap clip(Bitmap src, int x, int y, int width, int height, boolean recycle) {

        Bitmap ret = Bitmap.createBitmap(src, x, y, width, height);
        if (recycle && !src.isRecycled()) {
            src.recycle();
        }
        return ret;
    }


    public static Bitmap compositeBitmap(Bitmap firstBitmap, Bitmap secondBitmap) {
        Bitmap bitmap = Bitmap.createBitmap(firstBitmap.getWidth(), firstBitmap.getHeight(),
                firstBitmap.getConfig());
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(firstBitmap, new Matrix(), null);
        canvas.drawBitmap(secondBitmap, 0, 0, null);
        return bitmap;
    }

    public static File bitmapToFile(File dir, Bitmap bitmapBg, Bitmap bitmapFg) {

        return bitmapToFile(dir, compositeBitmap(bitmapBg, bitmapFg));
    }

    public static File bitmapToFile(File dir, Bitmap bitmap) {

        FileOutputStream fos = null;

        File file = new File(dir, "IMG_" + System.currentTimeMillis() + "_" + AndroidUtils.getDeviceId() + ".png");
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(FORMAT, QUALITY, bos);

            byte[] bitmapdata = bos.toByteArray();
            fos = new FileOutputStream(file);
            fos.write(bitmapdata);
            fos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(fos);
        }
        return file;
    }

    public static Bitmap conver(int width, int height, Bitmap bitmapSrc) {
        if (bitmapSrc.getWidth() <= 240 && bitmapSrc.getHeight() <= 240) {
            return bitmapSrc;
        }

        Bitmap scale = scale(bitmapSrc, 240, 320, true);

        return clip(scale, 0, 40, width, height, true);
    }
}
